import { defineStore } from 'pinia';
import { login, logout } from '@/api/auth';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {
      username: localStorage.getItem('username') || '',
      nickname: localStorage.getItem('nickname') || '',
      avatar: localStorage.getItem('avatar') || ''
    },
    isLoggedIn: !!localStorage.getItem('token')
  }),
  
  actions: {
    async login(loginForm: { username: string; password: string }) {
      try {
        const res: any = await login(loginForm);
        this.token = res.tokenValue;
        this.userInfo = res.user;
        this.isLoggedIn = true;
        
        // 保存到localStorage
        localStorage.setItem('username', res.user.username);
        localStorage.setItem('nickname', res.user.nickname);
        localStorage.setItem('avatar', res.user.avatar);
        localStorage.setItem('token', res.tokenValue);
        
        return res;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    
    // async logout() {
    //   try {
    //     await logout();
    //     this.resetState();
    //     return true;
    //   } catch (error) {
    //     return Promise.reject(error);
    //   }
    // },
    
    resetState() {
      this.token = '';
      this.userInfo = { username: '', nickname: '', avatar: '' };
      this.isLoggedIn = false;
      localStorage.removeItem('username');
      localStorage.removeItem('nickname');
      localStorage.removeItem('avatar');
      localStorage.removeItem('token');
    },

    setUser(user) {
      this.userInfo = user;
      this.isLoggedIn = true;
      this.token = user.token;

      // 保存到localStorage
      localStorage.setItem('username', user.username);
      localStorage.setItem('nickname', user.nickname);
      localStorage.setItem('avatar', user.avatar);
      localStorage.setItem('token', user.token);
    },

    logout() {
      this.userInfo = { username: '', nickname: '', avatar: '' };
      this.isLoggedIn = false;
      this.token = '';

      // 清除localStorage
      localStorage.removeItem('username');
      localStorage.removeItem('nickname');
      localStorage.removeItem('avatar');
      localStorage.removeItem('token');
    }
  }
}); 